package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.entity.FiFinance;
import com.example.demo.entity.BdMerchant;
import com.example.demo.mapper.FinanceMapper;
import com.example.demo.mapper.MerchantMapper;
import com.example.demo.service.FinanceService;
import com.example.demo.utils.RMBChange;
import net.sourceforge.pinyin4j.PinyinHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
* @author fqc
* @description 针对表【finance】的数据库操作Service实现
* @createDate 2023-11-21 08:57:09
*/
@Service
public class FinanceServiceImpl extends ServiceImpl<FinanceMapper, FiFinance> implements FinanceService {

    @Autowired
    private FinanceMapper financeMapper;

    @Autowired
    private MerchantMapper merchantMapper;

    @Value("${file.path}")
    private String filePath;

    /**
     *
     * @author fqc
     * @date 2023/11/22 12:40
     * @param merchantName
    * @return java.lang.String
     */
    public String getPinYin(String merchantName) {
        StringBuilder pinyinInitials = new StringBuilder();

        // 获取每个汉字的拼音首字母
        for (char c : merchantName.toCharArray()) {
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c);
            if (pinyinArray != null && pinyinArray.length > 0) {
                pinyinInitials.append(pinyinArray[0].charAt(0));
            }
        }
        return pinyinInitials.toString().toUpperCase();
    }

    @Override
    public List getMerchant(String name, List<String> list) {
        List<BdMerchant> bdMerchants =new ArrayList<>();
        for (String merchantInfo : list) {
            LambdaQueryWrapper<BdMerchant> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(BdMerchant::getName,merchantInfo);
            queryWrapper.orderByDesc(BdMerchant::getUpdateTime);
            queryWrapper.last("limit 1");
            BdMerchant m= merchantMapper.selectOne(queryWrapper);
            if(null == m){
                BdMerchant mer =new BdMerchant();
                mer.setMainBusiness("");
                mer.setContractNumber("");
                bdMerchants.add(mer);
            }else {
                bdMerchants.add(m);
            }
        }

        return bdMerchants;
    }

    @Override
    public List<FiFinance> getInfoByMerchant(String merchant, String [] ids) {
        try{
            LambdaQueryWrapper<FiFinance> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(FiFinance::getMerchant,merchant);
            queryWrapper.in(FiFinance::getId,ids);
            List<FiFinance> fiFinanceList =financeMapper.selectList(queryWrapper);
            for (int i = 0; i< fiFinanceList.size(); i++){
                FiFinance fiFinance = fiFinanceList.get(i);
                Integer index=i+1;
                fiFinance.setNumber(index.toString());
            }
            return fiFinanceList;
        }catch (Exception e){
            e.printStackTrace();
        }
            return null;
    }

    @Override
    public Map<Integer, List<Map<String, Object>>> getMaps(String checkDeptIds) {
        Map<Integer, List<Map<String, Object>>> maps=new HashMap<>();
        Set<String> uniqueMerchants = new HashSet<>();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");

        String[] ids = checkDeptIds.split(",");
        for(int i=0;i<ids.length;i++){
            FiFinance fiFinance =financeMapper.selectById(ids[i]);
            String merchant = fiFinance.getMerchant();
            if (!uniqueMerchants.contains(merchant)) {
                Map<String, Object> map = new HashMap<>();
                map.put("merchant", merchant);
                uniqueMerchants.add(merchant);
            }
        }

        List<String> uniqueMerchantsList = new ArrayList<>(uniqueMerchants);

        for (int i = 0; i < uniqueMerchantsList.size(); i++) {
            List<Map<String, Object>> mapList=new ArrayList<>();
            String merchant =uniqueMerchantsList.get(i);
            List<FiFinance> fiFinanceList = this.getInfoByMerchant(merchant,ids);
            // 计算outstandingAmount总和
            BigDecimal outstandingAmount = BigDecimal.ZERO;
            for (FiFinance fiFinance : fiFinanceList) {
                BigDecimal amountAvailable = new BigDecimal(fiFinance.getOutstandingAmount().toString());
                outstandingAmount = outstandingAmount.add(amountAvailable);
            }
            List<BdMerchant> mList=this.getMerchant(merchant,uniqueMerchantsList);
            Map<String, Object> map = new HashMap<>();
            map.put("orderId", this.getPinYin(merchant)+sdf.format(new Date()));
            map.put("sheetName", merchant);
            map.put("merchant", merchant);
            map.put("mainBusiness", mList.get(i).getMainBusiness());
            map.put("contractNumber", mList.get(i).getContractNumber());
            map.put("totalSmall", outstandingAmount);
            map.put("totalBig", RMBChange.convertCurrency(outstandingAmount.toString()));
            map.put("list", fiFinanceList);
            mapList.add(map);
            maps.put(i,mapList);
        }
        return maps;
    }


}




